package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

func checkErr(message string, err error) {
	// ignore os.EOF since it's not really an error...
	if err != nil && err != io.EOF {
		os.Stderr.WriteString(message + "\n" + err.Error() + "\n")
		os.Exit(1)
	}
}

func main() {
	fmt.Print("请输入远程服务IP和端口，如127.0.0.1:8848\n请输入：")
	var remoteAddress string
	_, err := fmt.Scan(&remoteAddress)
	checkErr("IP和端口输入错误", err)

	remoteUDPAddr, err := net.ResolveUDPAddr("", remoteAddress)
	checkErr("Unable to bind:", err)

	fmt.Print("请输入本地服务IP和端口，如127.0.0.1:8849\n请输入：")
	var localAddress string
	_, err = fmt.Scan(&localAddress)
	checkErr("IP和端口输入错误", err)

	localUDPAddr, err := net.ResolveUDPAddr("", localAddress)
	checkErr("Unable to bind:", err)
	conn, err := net.DialUDP("udp", localUDPAddr, remoteUDPAddr)
	checkErr("Unable to connect:", err)
	defer conn.Close()

	// 双工接收数据
	go response(conn)

	// write to the server
	fmt.Println("请输入内容：")

	for {
		var msg string
		_, err = fmt.Scan(&msg)
		checkErr("Unable to send:", err)
		_, err = conn.Write([]byte(msg))
		checkErr("Unable to send:", err)
	}
}

func response(conn *net.UDPConn) {
	// read from the server
	for {
		response := make([]byte, 64)
		n, _, err := conn.ReadFromUDP(response)
		checkErr("Unable to get response:", err)

		fmt.Printf("Response:%s\n", string(response[:n]))
	}
}
